package com.fabiodocarmo.calendario.dao.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author Fábio do Carmo Gomes
 * @version v-0.1 - 19/03/2009
 * @since 19/03/2009
 */
public class HibernateUtil {

    /**
     * Variável estática para a fábrica de sessões.
     */
    private static final SessionFactory sessionFactory;

    /**
     * Bloco estático de inicialização do Hibernate.
     */
    static {
        try {
            sessionFactory = new AnnotationConfiguration()
                .configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log exception!
            throw new ExceptionInInitializerError(ex);
        }
    }

    @SuppressWarnings("unchecked")
    public static final ThreadLocal session = new ThreadLocal();

    @SuppressWarnings("unchecked")
    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            // Store it in the ThreadLocal variable
            session.set(s);
        }
        return s;
    }

    @SuppressWarnings("unchecked")
    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}
